import { Component, OnInit } from '@angular/core'
import { NewPageBaseClass } from '@shared/classes/NewPageBaseClass'
import { MerchantStoreService } from '../merchant-store.service'
import { NzMessageService } from 'ng-zorro-antd'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Merchant, ICreateMerchant } from '@shared/interfaces/merchant'
import { MustMatch } from 'app/utils/helpers'
import { merchantauthPasswordReg } from 'app/utils/contraints'
import { I18NService } from '@core'

@Component({
  selector: 'app-merchant-new-trade',
  templateUrl: './trade.component.html',
})
export class MerchantNewTradeComponent extends NewPageBaseClass implements OnInit {
  merchant: Merchant
  validateForm: FormGroup
  errorTips = {}

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    private fb: FormBuilder,
    private merchantStore: MerchantStoreService,
  ) {
    super(msg, i18n)
  }

  ngOnInit() {
    this.initErrorTips()
    this.merchantStore.value$.subscribe(createMerchant => {
      this.merchant = createMerchant.merchant
      this.initValidateForm()
    })
  }

  initErrorTips(): void {
    this.errorTips = {
      authPassword: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('BIZ.MERCHANT.OTHER.TRADE.AUTH_CODE') }),
        maxlength: this.trans('VALIDATION.FIXED_LENGTH', { length: 6 }),
        minlength: this.trans('VALIDATION.FIXED_LENGTH', { length: 6 }),
        pattern: this.trans('VALIDATION.PATTERN.NUMBER_ONLY'),
      },
    }
  }

  initValidateForm(): void {
    const { tradeInfo } = this.merchant.common
    this.validateForm = this.fb.group(
      {
        authPassword: [
          tradeInfo.authPassword,
          [
            Validators.required,
            Validators.maxLength(6),
            Validators.minLength(6),
            Validators.pattern(merchantauthPasswordReg),
          ],
        ],
        authPasswordCF: [tradeInfo.authPasswordCF, [Validators.required]],
      },
      {
        validator: MustMatch('authPassword', 'authPasswordCF'),
      },
    )
  }

  checkValid(): boolean {
    const valid = this.validateForm.valid
    if (valid) {
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    } else {
      this.makeAllControlDirty(this.validateForm)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    }
    return valid
  }

  pushDataToStore(): void {
    this.fullfilData(this.validateForm.value)
    this.merchantStore.updateValue({ merchant: this.merchant } as ICreateMerchant)
  }

  private fullfilData(value): void {
    const { common } = this.merchant
    common.tradeInfo.authPassword = value.authPassword
    common.tradeInfo.authPasswordCF = value.authPasswordCF
  }
}
